package com.ruoyi.yljf.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.RandomUtil;
import com.alipay.api.domain.CaptureCreateOrder;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BizCodeEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.yljf.domain.*;
import com.ruoyi.yljf.domain.dto.CreateDTO.CerateOrderDTO;
import com.ruoyi.yljf.domain.dto.OrderDTO;
import com.ruoyi.yljf.domain.vo.OrderVO;
import com.ruoyi.yljf.mapper.*;
import com.ruoyi.yljf.service.IGoodsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.service.IOrderService;

import javax.annotation.Resource;

/**
 * 订单Service业务层处理
 * 
 * @author metaee
 * @date 2025-03-26
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private IGoodsOrderService goodsOrderService;
	@Resource
	private GoodsOrderMapper goodsOrderMapper;
	@Resource
	private CourseMapper courseMapper;
	@Resource
	private ActiveMapper activeMapper;
    
    /**
     * 查询订单列表
     * 
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
    	LambdaQueryWrapper<Order> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(order.getNumber())) {
			queryWrapper.eq(Order::getNumber, order.getNumber());
		}
        if (StringUtils.isNotNull(order.getUserId())) {
			queryWrapper.eq(Order::getUserId, order.getUserId());
		}
        if (ObjectUtils.isNotEmpty(order.getOrderType())) {
			queryWrapper.eq(Order::getOrderType, order.getOrderType());
		}
        if (StringUtils.isNotNull(order.getStatus())) {
			queryWrapper.eq(Order::getStatus, order.getStatus());
		}
        if (StringUtils.isNotNull(order.getDishId())) {
			queryWrapper.eq(Order::getDishId, order.getDishId());
		}
        if (StringUtils.isNotEmpty(order.getName())) {
			queryWrapper.like(Order::getName, order.getName());
		}
        if (StringUtils.isNotEmpty(order.getImage())) {
			queryWrapper.eq(Order::getImage, order.getImage());
		}
        if (StringUtils.isNotNull(order.getAmount())) {
			queryWrapper.eq(Order::getAmount, order.getAmount());
		}
        if (StringUtils.isNotNull(order.getCheckoutTime())) {
			queryWrapper.eq(Order::getCheckoutTime, order.getCheckoutTime());
		}
        if (StringUtils.isNotNull(order.getFinishTime())) {
			queryWrapper.eq(Order::getFinishTime, order.getFinishTime());
		}
        if (StringUtils.isNotEmpty(order.getIsSend())) {
			queryWrapper.eq(Order::getIsSend, order.getIsSend());
		}
        return orderMapper.selectList(queryWrapper);
    }



	@Override
	public List<OrderVO> selectOrders(List<Order> orders) {
		List<Long> sendUserIds = orders.stream()
				.map(Order::getSendUserId) // 提取 sendUserId 字段
				.collect(Collectors.toList());
		Map<Long, User> userMap = new HashMap<Long, User>();

		if (ObjectUtils.isNotEmpty(sendUserIds)) {
			List<User> users = userMapper.selectBatchIds(sendUserIds);
			userMap = users.stream()		//赠送人信息对象
					.collect(Collectors.toMap(User::getUserId,  user -> user));
		}

		Map<Long, User> finalUserMap = userMap;
		List<OrderVO> collect = orders.stream().map(item -> {
			OrderVO orderVO = new OrderVO(item);
			Long sendUserId = orderVO.getSendUserId();  // 获取当前 orderVO 的 sendUserId
			User user = finalUserMap.get(sendUserId);  // 从 userMap 中查找对应的 User 对象
			if (user != null) {
				orderVO.setSendUserName(user.getUserName());  // 如果找到 User，设置 giveUserName
			}
			return orderVO;
		}).collect(Collectors.toList());

		return collect;
	}

	@Override
	public List<Order> selectAllOrder(OrderDTO orderDTO) {
		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>(Order.class);
		queryWrapper.eq(Order::getOrderType, 1);		//查询课程
		if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 1) {		//我待付款的订单
			queryWrapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 2){		//我已完成的订单
			queryWrapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 3) {		//我已赠送的订单
			queryWrapper.eq(Order::getIsSend,"Y")
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 4) {		//我已接收的订单
			queryWrapper.eq(Order::getSendUserId,SecurityUtils.getUserId());
		}else {			//查询全部订单  我购买的和我收到的
			queryWrapper.and(wrapper -> wrapper.eq(Order::getUserId,  SecurityUtils.getUserId()) // user_id = 16
					.or() // 或
					.eq(Order::getSendUserId,  SecurityUtils.getUserId()));
		}
		return orderMapper.selectList(queryWrapper);
	}

	@Override
	public List<Order> selectActiveOrder(OrderDTO orderDTO) {
		LambdaQueryWrapper<Order> wapper = new LambdaQueryWrapper<>(Order.class);
		wapper.eq(Order::getOrderType, 2);		//查询活动
		if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 1) {		//待付款
			wapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 2){		//已完成
			wapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 3) {		//已赠送
			wapper.eq(Order::getIsSend,"Y")
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 4) {		//已接收
			wapper.eq(Order::getSendUserId,SecurityUtils.getUserId());
		}else {			//查询全部订单  我购买的和我收到的
			wapper.and(wrapper -> wrapper.eq(Order::getUserId,  SecurityUtils.getUserId()) // user_id = 16
					.or() // 或
					.eq(Order::getSendUserId,  SecurityUtils.getUserId()));
		}
		return orderMapper.selectList(wapper);
	}

	@Override
	public List<Order> selectBookOrder(OrderDTO orderDTO) {
		LambdaQueryWrapper<Order> wapper = new LambdaQueryWrapper<>(Order.class);
		wapper.eq(Order::getOrderType, 3);		//查询书籍
		if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 1) {		//待付款
			wapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 2){		//已完成
			wapper.eq(Order::getStatus, orderDTO.getStatus())
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 3) {		//已赠送
			wapper.eq(Order::getIsSend,"Y")
					.eq(Order::getUserId,SecurityUtils.getUserId());
		}else if (ObjectUtils.isNotEmpty(orderDTO.getStatus()) && orderDTO.getStatus() == 4) {		//已接收
			wapper.eq(Order::getSendUserId,SecurityUtils.getUserId());
		}else {			//查询全部订单  我购买的和我收到的
			wapper.and(wrapper -> wrapper.eq(Order::getUserId,  SecurityUtils.getUserId()) // user_id = 16
					.or() // 或
					.eq(Order::getSendUserId,  SecurityUtils.getUserId()));
		}
		return orderMapper.selectList(wapper);
	}

	@Override
	public List<GoodsOrder> selectPointsOrder(OrderDTO orderDTO) {
		LambdaQueryWrapper<GoodsOrder> wapper = new LambdaQueryWrapper<>(GoodsOrder.class);
		if (ObjectUtils.isNotEmpty(orderDTO.getStatus())) {		//按照传的参数查询对应的数据
			wapper.eq(GoodsOrder::getStatu, orderDTO.getStatus())
					.eq(GoodsOrder::getUserId,SecurityUtils.getUserId());
		}else {			//查询全部订单
			wapper.eq(GoodsOrder::getUserId,SecurityUtils.getUserId());
		}
		return goodsOrderMapper.selectList(wapper);
	}

	@Override
	public AjaxResult createOrder(CerateOrderDTO dto) {
		Order order = new Order();
		order.setUserId(SecurityUtils.getUserId());
		String outTradeNum = System.currentTimeMillis() + RandomUtil.randomNumbers(6);
		order.setNumber(outTradeNum);
		order.setOrderType(dto.getOrderType());
		order.setDishId(dto.getDishId());
		BigDecimal amount = new BigDecimal("0.00");
//		order.setStatus(1L);	//数据库配置了默认值
		if (dto.getOrderType() == 1 ) {		//课程
			Course course = courseMapper.selectById(dto.getDishId());
			if (ObjectUtils.isNotEmpty(course)) {
//				order.setAmount(course.getPrice());
				order.setName(course.getName());
				order.setImage(course.getImg());
				order.setPayMethod("qizhi");
				amount =course.getPrice();
			}else {
				return AjaxResult.buildResult(BizCodeEnum.SELECT_ERROR);
			}
		} else if (dto.getOrderType() == 2 ) {
			Active active = activeMapper.selectById(dto.getDishId());
			if (ObjectUtils.isNotEmpty(active)) {
				order.setName(active.getActiveName());
				order.setImage(active.getActiveImg());
				order.setPayMethod("qizhi");	//Fixme 活动使用币种未知，目前使用启智币
				amount = active.getActivePrice();
			}else {
				return AjaxResult.buildResult(BizCodeEnum.SELECT_ERROR);
			}
		} else if (dto.getOrderType() == 3) {
			//TODO   书籍暂时未接入
//			amount = String.valueOf(active.getActivePrice());		//书籍价格
		}else{
			return AjaxResult.buildResult(BizCodeEnum.SELECT_ERROR);
		}
		order.setAmount(amount);
		//判断积分是否足够
		User user = userMapper.selectById(SecurityUtils.getUserId());
		int result = amount.compareTo(user.getQizhiCoin());
		if (result > 0) {		//订单金额比余额高
			orderMapper.insert(order);	//新增订单
			return AjaxResult.buildResult(BizCodeEnum.LACK_BALANCE);	//余额不足
		}else {			//余额足够支付订单
			order.setStatus(2l);
			order.setCheckoutTime(new Date());
			order.setFinishTime(new Date());
			orderMapper.insert(order);	//新增订单
			//更改用户余额
			user.setQizhiCoin(user.getQizhiCoin().subtract(amount));
			userMapper.updateById(user);
		}

		return AjaxResult.success();
	}

	@Override
	public AjaxResult toPay(String number) {
		Order order = orderMapper.selectOne(new LambdaQueryWrapper<>(Order.class).eq(Order::getNumber, number).eq(Order::getStatus,1));
		if (ObjectUtils.isNotEmpty(order)) {
			User user = userMapper.selectById(SecurityUtils.getUserId());
			int result = order.getAmount().compareTo(user.getQizhiCoin());
			if (result > 0) {		//订单金额比余额高
				return AjaxResult.buildResult(BizCodeEnum.LACK_BALANCE);	//余额不足
			}else {			//余额足够支付订单
				order.setStatus(2l);
				order.setCheckoutTime(new Date());
				order.setFinishTime(new Date());
				orderMapper.updateById(order);
				//更改用户余额
				user.setQizhiCoin(user.getQizhiCoin().subtract(order.getAmount()));
				userMapper.updateById(user);
			}
		}else{
			return AjaxResult.buildResult(BizCodeEnum.SELECT_ERROR);
		}
		return AjaxResult.success();
	}


}
